package com.liyujie.networkrequest.pop;

import android.content.Context;
import android.text.Spannable;
import android.text.SpannableString;
import android.view.View;

import androidx.annotation.NonNull;

import com.liyujie.networkrequest.R;
import com.liyujie.networkrequest.listener.BeCommonCallback;
import com.liyujie.networkrequest.utils.serialport.OpenPortUtils;
import com.lxj.xpopup.core.CenterPopupView;

import org.angmarch.views.NiceSpinner;
import org.angmarch.views.OnSpinnerItemSelectedListener;
import org.angmarch.views.SpinnerTextFormatter;

import java.util.ArrayList;
import java.util.List;

public class SerialPortPopup extends CenterPopupView {
    /**
     * 串口号
     */
    private String SerialPort;

    public SerialPortPopup(@NonNull Context context) {
        super(context);
    }

    public SerialPortPopup(@NonNull Context context, String SerialPort) {
        super(context);
        this.SerialPort = SerialPort;
    }



    @Override
    protected int getImplLayoutId() {
        return R.layout.popup_serial_port;

    }


    @Override
    protected void onCreate() {
        super.onCreate();
        NiceSpinner mNiceSpinner = findViewById(R.id.mNiceSpinner);

        List<String> AllDeicesPathList = new ArrayList<>();
        for(String chuanKou : OpenPortUtils.getAllDeicesPath()){
            if(SerialPort.equals(chuanKou)){
                AllDeicesPathList.add(0,chuanKou);
            }else {
                AllDeicesPathList.add(chuanKou);
            }
        }
        SpinnerTextFormatter detectionPersonnel = new SpinnerTextFormatter<String>() {
            @Override
            public Spannable format(String chuanKou) {
                return new SpannableString(chuanKou);
            }
        };
        mNiceSpinner.setSpinnerTextFormatter(detectionPersonnel);
        mNiceSpinner.setSelectedTextFormatter(detectionPersonnel);
        mNiceSpinner.attachDataSource(AllDeicesPathList);
        mNiceSpinner.setOnSpinnerItemSelectedListener(new OnSpinnerItemSelectedListener() {
            @Override
            public void onItemSelected(NiceSpinner parent, View view, int position, long id) {
                SerialPort =  (String)mNiceSpinner.getSelectedItem();
            }
        });
        //取消
        findViewById(R.id.quXiao).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                dismiss();
            }
        });
        //确认
        findViewById(R.id.queRen).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if(null != beCommonCallback){
                    beCommonCallback.onBeCommonCallback(SerialPort);
                    dismiss();
                }
            }
        });
    }


    private BeCommonCallback beCommonCallback;
    public void setBeCommonCallback(BeCommonCallback beCommonCallback) {
        this.beCommonCallback = beCommonCallback;
    }
}
